import { init as initMenu } from '@/api/sys/menu'
import buildRouters from '@/utils/BuildRoutersByNameUtil'
import { resetRouter } from '@/router'
const state = {
  permissionRouters: [], // 从后台通过权限组装出来的权限路由
  buttonPermission: {},
  systemId: '',
  systemName: '',
  insideCount: 1
}

const mutations = {
  SET_MENUS: (state, menus) => {
    state.permissionRouters = menus
  },
  SET_BUTTON_PERMISSIOM: (state, buttonPermission) => {
    state.buttonPermission = buttonPermission
  },
  SET_SYSTEMID: (state, systemId) => {
    state.systemId = systemId
  }
}

const actions = {
  // get menus info
  async getMenus({ commit, state }) {
    return new Promise((resolve, reject) => {
      initMenu(state.token).then(response => {
        const { data } = response

        // 构建动态路由
        const routerMenus = buildRouters(data)
        commit('SET_MENUS', routerMenus.routers) // 设置权限路由
        commit('SET_BUTTON_PERMISSIOM', routerMenus.buttonPermission) // 设置权限路由
        // console.log(routerMenus)
        // commit('permissionRouters', routerMenus)
        resolve(routerMenus.routers)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 在用户退出时，需要调用此方法
  resetMenus({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_MENUS', [])
      resetRouter()
      resolve([])
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
